import { getToken, setToken, removeToken } from '@/utils/auth'

// 村赤用户令牌和角色信息
const state = {
    userName: localStorage.getItem("name"),
    avatar: localStorage.getItem("avatar"),
    token: getToken(),
    roles: [] //角色
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token;
    },
    SET_ROLES: (state, roles) => {
        state.roles = roles;
    },
    SET_NAME: (state, name) => {
        state.userName = name;
    },
    SET_AVATAR: (state, url) => {
        state.avatar = url;
    }
};

const actions = {
    // 用户登录
    login({ commit }, userInfo) {
        console.log(userInfo)
        const { userType } = userInfo.type;
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                if (userType === 0 || userType === 1) {
                    // 写入cookie
                    setToken(userInfo.token);
                    // 保存状态
                    commit('SET_TOKEN', userType);
                    commit('SET_NAME', userInfo.userName);
                    commit('SET_AVATAR', userInfo.avatarUrl);
                    localStorage.setItem("avatar", userInfo.avatarUrl);
                    localStorage.setItem("name", userInfo.userName);
                    localStorage.setItem("ROLES", userInfo.type);
                    resolve()
                } else {
                    reject({})
                }
            }, 1000)
        })
    },
    // 获取用户角色信息
    getInfo({ commit, state }) {
        return new Promise((resolve) => {
            setTimeout(() => {
                let res = localStorage.getItem("ROLES");
                const roles = res === 0 || res === '0' ? ['admin'] : ['jerry']
                commit('SET_ROLES', roles)
                resolve({ roles })
            }, 1000)
        })
    },
    // 重置令牌
    resetToken({ commit }) {
        return new Promise(resolve => {
            commit('SET_TOKEN', '')
            commit('SET_ROLES', [])
            removeToken();
            resolve()
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}